package cn.le.thread;

import java.util.concurrent.locks.ReentrantLock;

public class TwoThreadWaitNotify{

    public int start = 1;

    public boolean flag = false;


    public static void main(String[] args) {
        TwoThreadWaitNotify twoThread = new TwoThreadWaitNotify();
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(new OuNum(twoThread,lock));
        t1.setName("A");


        Thread t2 = new Thread(new JiNum(twoThread,lock));
        t2.setName("B");

        t1.start();
        t2.start();
    }

}

/**
 * 偶数线程
 */
class OuNum implements Runnable {

    private TwoThreadWaitNotify number;
    private ReentrantLock lock;
    public OuNum(TwoThreadWaitNotify number, ReentrantLock lock) {
        this.number = number;
        this.lock = lock;
    }

    public void run() {

        while (number.start <= 100) {
            //synchronized (TwoThreadWaitNotify.class) {
            lock.lock();
                System.out.println("偶数线程抢到锁了");
                if (number.flag) {
                    System.out.println(Thread.currentThread().getName() + "+-+偶数" + number.start);
                    number.start++;

                    number.flag = false;
                    this.notify();

                }else {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            //}
            lock.unlock();
        }
    }
}
/**
 * 奇数线程
 */
class JiNum implements Runnable {

    private TwoThreadWaitNotify number;
    private ReentrantLock lock;

    public JiNum(TwoThreadWaitNotify number,ReentrantLock lock) {
        this.number = number;
        this.lock = lock;
    }

    public void run() {
        while (number.start <= 100) {
            //synchronized (TwoThreadWaitNotify.class) {
                lock.lock();
                System.out.println("奇数线程抢到锁了");
                if (!number.flag) {
                    System.out.println(Thread.currentThread().getName() + "+-+奇数" + number.start);
                    number.start++;

                    number.flag = true;

                    this.notify();
                }else {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.unlock();
            }

    }
}
